package com.wejoy.video.middle.station.admin.controller.workorder;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.wejoy.video.middle.station.admin.controller.BaseController;
import com.wejoy.video.middle.station.admin.util.CurrentUserUtils;
import com.wejoy.video.middle.station.data.annotation.RoleCheck;
import com.wejoy.video.middle.station.data.domain.PageResult;
import com.wejoy.video.middle.station.data.domain.system.SysDept;
import com.wejoy.video.middle.station.data.domain.system.SysUser;
import com.wejoy.video.middle.station.data.domain.workorder.OrderPhotoLib;
import com.wejoy.video.middle.station.data.domain.workorder.WorkOrderInfo;
import com.wejoy.video.middle.station.data.domain.workorder.WorkOrderProcess;
import com.wejoy.video.middle.station.data.domain.workorder.WorkOrderReview;
import com.wejoy.video.middle.station.data.enums.dict.EnumDeptType;
import com.wejoy.video.middle.station.data.enums.dict.EnumProcessType;
import com.wejoy.video.middle.station.data.enums.dict.EnumWorkOrderReviewStatus;
import com.wejoy.video.middle.station.data.enums.dict.EnumWorkOrderStatus;
import com.wejoy.video.middle.station.data.exception.BusinessException;
import com.wejoy.video.middle.station.data.service.evs.IEvsHttpService;
import com.wejoy.video.middle.station.data.service.system.ISysDeptService;
import com.wejoy.video.middle.station.data.service.workorder.IOrderPhotoLibService;
import com.wejoy.video.middle.station.data.service.workorder.IWorkOrderInfoService;
import com.wejoy.video.middle.station.data.service.workorder.IWorkOrderProcessService;
import com.wejoy.video.middle.station.data.service.workorder.IWorkOrderReviewService;
import com.wejoy.video.middle.station.data.util.StringUtils;
import com.wejoy.video.middle.station.data.util.WJAssert;
import com.wejoy.video.middle.station.data.vo.RespJSON;
import com.wejoy.video.middle.station.data.vo.workorder.WorkOrderDetailVO;
import com.wejoy.video.middle.station.data.vo.workorder.WorkOrderStatisticsVO;
import com.wejoy.video.middle.station.data.vo.workorder.WorkorderExcelVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 工单主表
 *
 * @author miracle_j
 * @date 2022年11月16日 17:28:50
 */
@RestController
@RequestMapping("/workorder/workOrderInfo")
public class WorkOrderInfoController extends BaseController {

    @Autowired
    private IWorkOrderInfoService workOrderInfoService;
    @Autowired
    private IWorkOrderProcessService workOrderProcessService;
    @Autowired
    private IWorkOrderReviewService workOrderReviewService;
    @Value("${qiniu.prefix}")
    private String imagePrefix;
    @Autowired
    private IOrderPhotoLibService orderPhotoLibService;
    @Autowired
    private IEvsHttpService evsHttpService;
    @Autowired
    private ISysDeptService sysDeptService;

    /**
     * 保存或更新
     *
     * @param workOrderInfoReq workOrderInfoReq
     * @return RespJSON
     */
    @PostMapping("/save")
    @RoleCheck(name = "work_order_edit")
    public RespJSON save(@RequestBody WorkOrderInfo workOrderInfoReq, @SessionAttribute(CurrentUserUtils.SYSTEM_USER) SysUser loginSysUser) {
        workOrderInfoService.save(workOrderInfoReq, loginSysUser.getUserName());
        return RespJSON.success();
    }

//    /**
//     * 分页查询
//     *
//     * @param workOrderInfoReq workOrderInfoReq
//     * @return RespJSON
//     */
//    @PostMapping("/getPageList")
//    @RoleCheck(name = "order:workOrderInfoList:list")
//    public RespJSON getPageList(@RequestBody WorkOrderInfo workOrderInfoReq,@SessionAttribute(CurrentUserUtils.SYSTEM_USER) SysUser loginSysUser) {
//        boolean contains = loginSysUser.getSysResourceIdentityList().contains("work_order_list_all");
//        if(contains){
//            int count = workOrderInfoService.getCount(workOrderInfoReq);
//            List<WorkOrderInfo> list = new ArrayList<>();
//            if (count > 0) {
//                list = workOrderInfoService.getPageList(workOrderInfoReq);
//                list.parallelStream().forEach(item -> {
//                    item.setOrderButton(loginSysUser.getSysResourceIdentityList().contains("work_order_accept"));
//                    item.setApprovalButton(loginSysUser.getSysResourceIdentityList().contains("work_order_review"));
//                    item.setReminderButton(loginSysUser.getSysResourceIdentityList().contains("work_order_remind"));
//                    item.setImageUrl(imagePrefix+item.getImageUrl());
//                });
//            }
//            PageResult result = new PageResult(workOrderInfoReq.getPageNo(), workOrderInfoReq.getPageSize(), count, list);
//            return RespJSON.success(result);
//        }else{
//            if(CollectionUtils.isEmpty(loginSysUser.getManageDeptIdList())){
//                return RespJSON.success();
//            }
//            workOrderInfoReq.setDataPermissionDeptIds(loginSysUser.getManageDeptIdList());
//            int count = workOrderInfoService.getDataPermissionCount(workOrderInfoReq);
//            List<WorkOrderInfo> list = new ArrayList<>();
//            if (count > 0) {
//                list = workOrderInfoService.getDataPermissionPageList(workOrderInfoReq);
//                list.parallelStream().forEach(item -> {
//                    item.setImageUrl(imagePrefix+item.getImageUrl());
//                    item.setOrderButton(loginSysUser.getSysResourceIdentityList().contains("work_order_accept"));
//                    item.setApprovalButton(loginSysUser.getSysResourceIdentityList().contains("work_order_review"));
//                    item.setReminderButton(loginSysUser.getSysResourceIdentityList().contains("work_order_remind"));
//                    if(item.getOrderStatus().equals(EnumWorkOrderStatus.ACCEPT_UNPROCESSED.getCode())||item.getOrderStatus().equals(EnumWorkOrderStatus.ACCEPT_PREPROCESSING.getCode())){
//                        item.setCanHandle(item.getAcceptUserId().equals(loginSysUser.getId()));
//                    }
//                });
//            }
//            PageResult result = new PageResult(workOrderInfoReq.getPageNo(), workOrderInfoReq.getPageSize(), count, list);
//            return RespJSON.success(result);
//        }
//    }

    /**
     * 分页查询
     *
     * @param workOrderInfoReq workOrderInfoReq
     * @return RespJSON
     */
    @PostMapping("/getPageList")
    @RoleCheck(name = "order:workOrderInfoList:list")
    public RespJSON getPageList(@RequestBody WorkOrderInfo workOrderInfoReq,@SessionAttribute(CurrentUserUtils.SYSTEM_USER) SysUser loginSysUser) {
        if(workOrderInfoReq.getDeptId() != null){
            SysDept dept = sysDeptService.getOneById(workOrderInfoReq.getDeptId());
            if(dept!=null){
                if(dept.getDeptType()!=null&&dept.getDeptType().equals(EnumDeptType.DEPT_SUBSIDIARY.getCode())){
                    workOrderInfoReq.setCompanyId(workOrderInfoReq.getDeptId());
                    workOrderInfoReq.setDeptId(null);
                }
//                if(dept.getDeptType()!=null&&dept.getDeptType().equals(EnumDeptType.DEPT_DISPATCH_CENTER.getCode())){
//                    workOrderInfoReq.setDispatchCenterId(workOrderInfoReq.getDeptId());
//                    workOrderInfoReq.setDeptId(null);
//                }
            }
        }
        if(!CollectionUtils.isEmpty(loginSysUser.getDataPermissionDeptIds())&&loginSysUser.getDataPermissionDeptIds().size()==1&&loginSysUser.getDataPermissionDeptIds().get(0)==3){
            int count = workOrderInfoService.getCount(workOrderInfoReq);
            List<WorkOrderInfo> list = new ArrayList<>();
            if (count > 0) {
                list = workOrderInfoService.getPageList(workOrderInfoReq);
            }
            PageResult result = new PageResult(workOrderInfoReq.getPageNo(), workOrderInfoReq.getPageSize(), count, list);
            return RespJSON.success(result);
        }else{
            if(CollectionUtils.isEmpty(loginSysUser.getDataPermissionDeptIds())){
                return RespJSON.success();
            }
            workOrderInfoReq.setDataPermissionDeptIds(loginSysUser.getDataPermissionDeptIds());
            int count = workOrderInfoService.getDataPermissionCount(workOrderInfoReq);
            List<WorkOrderInfo> list = new ArrayList<>();
            if (count > 0) {
                list = workOrderInfoService.getDataPermissionPageList(workOrderInfoReq);
            }
            PageResult result = new PageResult(workOrderInfoReq.getPageNo(), workOrderInfoReq.getPageSize(), count, list);
            return RespJSON.success(result);
        }
    }

    /**
     * 下载excel文件
     */
    @GetMapping("/excel")
    public void doDownLoad(Long updateTimeEnd,Long createTimeStart,
                           String businessScenario,Long orderStatus,
                           String managerUserName,String managerUserPhone,
                           String acceptUserName,Long acceptTimeEnd,Long acceptTimeStart, Long deptId,
                           String deptName,HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("工单信息文件"+createTimeStart+"_"+updateTimeEnd, "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        WorkOrderInfo workOrderInfo = new WorkOrderInfo();
        if(updateTimeEnd.equals(0L) || updateTimeEnd.equals(0L)){
            throw new BusinessException("请筛选日期");
        }
        if(!StringUtils.isEmpty(businessScenario)){
            workOrderInfo.setBusinessScenario(businessScenario);
        }
        if(!StringUtils.isEmpty(deptName)){
            workOrderInfo.setDeptName(deptName);
        }
        if(!ObjectUtils.isEmpty(deptId)){
            workOrderInfo.setDeptId(deptId);
        }
        if(acceptTimeStart!=null){
            workOrderInfo.setAcceptTimeStart(new Date(acceptTimeStart));
        }
        if(acceptTimeEnd!=null){
            workOrderInfo.setAcceptTimeEnd(new Date(acceptTimeEnd));
        }
        if(managerUserPhone!=null){
            workOrderInfo.setManagerUserPhone(managerUserPhone);
        }
        if(acceptUserName!=null){
            workOrderInfo.setAcceptUserName(acceptUserName);
        }
        if(managerUserName!=null){
            workOrderInfo.setManagerUserName(managerUserName);
        }
        workOrderInfo.setCreateTimeStart(new Date(createTimeStart));
        workOrderInfo.setUpdateTimeEnd(new Date(updateTimeEnd));
        int count = workOrderInfoService.getCount(workOrderInfo);
        List<WorkOrderInfo> list = new ArrayList<>();
        List<WorkorderExcelVO> excelVOList = new ArrayList<>();
        SysDept evsApiDept = new SysDept();
        evsApiDept.setParentId(-1);
        evsApiDept.setIncludeLower(true);
        List<SysDept> departments = evsHttpService.getDepartments(evsApiDept, evsHttpService.getToken());
        if (count > 0) {
            list = workOrderInfoService.getList(workOrderInfo);
            for (WorkOrderInfo orderInfo : list) {
                WorkorderExcelVO workorderExcelVO = new WorkorderExcelVO();
                BeanUtils.copyProperties(orderInfo,workorderExcelVO);
                workorderExcelVO.setFalseAlerm(orderInfo.getFalseAlerm()==null?"否":orderInfo.getFalseAlerm()==1?"是":"否");
                workorderExcelVO.setImageUrl(imagePrefix+workorderExcelVO.getImageUrl());
                departments.forEach(item->{
                    if(item.getId().equals(orderInfo.getCompanyId())){
                        workorderExcelVO.setDispatchCenterName(item.getName());
                        return;
                    }
                });
                workorderExcelVO.setOrderStatusValue(EnumWorkOrderStatus.getText(orderInfo.getOrderStatus()));
                //预处置信息
                WorkOrderProcess workOrderProcess = new WorkOrderProcess();
                workOrderProcess.setOrderId(orderInfo.getId());
                workOrderProcess.setType(EnumProcessType.PREPROCESSING.getCode());
                workOrderProcess.setPageNo(1);
                workOrderProcess.setPageSize(1);
                List<WorkOrderProcess> preprocessingList = workOrderProcessService.getList(workOrderProcess);
                if(!CollectionUtils.isEmpty(preprocessingList)){
                    workorderExcelVO.setPreprocessingDesc(preprocessingList.get(0).getProcessingDescription());
                }
                //处置信息
                workOrderProcess.setType(EnumProcessType.PROCESS.getCode());
                List<WorkOrderProcess> processList = workOrderProcessService.getList(workOrderProcess);
                if(!CollectionUtils.isEmpty(processList)){
                    workorderExcelVO.setDisposalDesc(processList.get(0).getProcessingDescription());
                }
                //审批信息
                WorkOrderReview workOrderReview = new WorkOrderReview();
                workOrderReview.setOrderId(orderInfo.getId());
                workOrderReview.setPageNo(1);
                workOrderReview.setPageSize(1);
                List<WorkOrderReview> reviewList = workOrderReviewService.getList(workOrderReview);
                if(!CollectionUtils.isEmpty(reviewList)){
                    workorderExcelVO.setAuditDesc(reviewList.get(0).getRemark());
                    workorderExcelVO.setAuditStatus(EnumWorkOrderReviewStatus.getText(reviewList.get(0).getReviewStatus()));
                    workorderExcelVO.setAuditTime(reviewList.get(0).getCreateTime());
                }
                excelVOList.add(workorderExcelVO);
            }
        }
        ExcelWriterBuilder write = EasyExcel.write(response.getOutputStream(), WorkorderExcelVO.class);
        ExcelWriterSheetBuilder excelWriterSheetBuilder = write.sheet("工单信息");
        excelWriterSheetBuilder.doWrite(excelVOList);
    }



    /**
     * 主键查询
     *
     * @param id id
     * @return RespJSON
     */
    @RequestMapping("/getOneById")
    public RespJSON getOneById(Long id) {
        return RespJSON.success(workOrderInfoService.getOneById(id));
    }

    /**
    * 审核
    *
    * @param id id
    * @return RespJSON
    */
    @PostMapping("/audit")
    public RespJSON audit(Long id, @SessionAttribute(CurrentUserUtils.SYSTEM_USER)SysUser loginSysUser) {
        WJAssert.notNull(id, "ID 不合法");
        workOrderInfoService.audit(id, loginSysUser.getUserName());
        return RespJSON.success();
    }

    /**
    * 取消审核
    *
    * @param id id
    * @return RespJSON
    */
    @PostMapping("/unaudit")
    public RespJSON unaudit(Long id, @SessionAttribute(CurrentUserUtils.SYSTEM_USER)SysUser loginSysUser) {
        WJAssert.notNull(id, "ID 不合法");
        workOrderInfoService.unaudit(id, loginSysUser.getUserName());
        return RespJSON.success();
    }

    /**
     * 工单统计
     * @return
     */
    @PostMapping("/getStatistics")
    public RespJSON getStatistics(@RequestBody WorkOrderInfo workOrderInfoEq,@SessionAttribute(CurrentUserUtils.SYSTEM_USER) SysUser loginSysUser) {
        workOrderInfoEq.setOrderStatus(null);
        if(workOrderInfoEq.getDeptId() != null){
            SysDept dept = sysDeptService.getOneById(workOrderInfoEq.getDeptId());
            if(dept!=null){
                if(dept.getDeptType()!=null&&dept.getDeptType().equals(EnumDeptType.DEPT_SUBSIDIARY.getCode())){
                    workOrderInfoEq.setCompanyId(workOrderInfoEq.getDeptId());
                    workOrderInfoEq.setDeptId(null);
                }
//                if(dept.getDeptType()!=null&&dept.getDeptType().equals(EnumDeptType.DEPT_DISPATCH_CENTER.getCode())){
//                    workOrderInfoEq.setDispatchCenterId(workOrderInfoEq.getDeptId());
//                    workOrderInfoEq.setDeptId(null);
//                }
            }
        }
        if(!CollectionUtils.isEmpty(loginSysUser.getDataPermissionDeptIds())&&loginSysUser.getDataPermissionDeptIds().size()==1&&loginSysUser.getDataPermissionDeptIds().get(0)==3){
            WorkOrderStatisticsVO workOrderStatisticsVO = new WorkOrderStatisticsVO();
            workOrderStatisticsVO.setTotalNumberOfWorkOrder(workOrderInfoService.getCount(workOrderInfoEq));
            workOrderInfoEq.setOrderStatus(EnumWorkOrderStatus.FINISHED.getCode());
            workOrderStatisticsVO.setQuantityDone(workOrderInfoService.getCount(workOrderInfoEq));
            workOrderStatisticsVO.setToDoQuantity(workOrderStatisticsVO.getTotalNumberOfWorkOrder()>workOrderStatisticsVO.getQuantityDone()?workOrderStatisticsVO.getTotalNumberOfWorkOrder()-workOrderStatisticsVO.getQuantityDone():0);
            return RespJSON.success(workOrderStatisticsVO);
        }else{
            if(CollectionUtils.isEmpty(loginSysUser.getDataPermissionDeptIds())){
                return RespJSON.success( new WorkOrderStatisticsVO(0,0,0));
            }
            workOrderInfoEq.setDataPermissionDeptIds(loginSysUser.getDataPermissionDeptIds());
            WorkOrderStatisticsVO workOrderStatisticsVO = new WorkOrderStatisticsVO();
            workOrderStatisticsVO.setTotalNumberOfWorkOrder(workOrderInfoService.getDataPermissionCount(workOrderInfoEq));
            workOrderInfoEq.setOrderStatus(EnumWorkOrderStatus.FINISHED.getCode());
            workOrderStatisticsVO.setQuantityDone(workOrderInfoService.getDataPermissionCount(workOrderInfoEq));
            workOrderStatisticsVO.setToDoQuantity(workOrderStatisticsVO.getTotalNumberOfWorkOrder()>workOrderStatisticsVO.getQuantityDone()?workOrderStatisticsVO.getTotalNumberOfWorkOrder()-workOrderStatisticsVO.getQuantityDone():0);
            return RespJSON.success(workOrderStatisticsVO);
        }

    }
    /**
     * 工单详情，查询处置列表+审核列表
     * @return
     */
    @GetMapping("/getDetail")
    public RespJSON getDetail(Long id) {
        WJAssert.notNull(id, "ID 不合法");
        WorkOrderDetailVO vo=new WorkOrderDetailVO();
        OrderPhotoLib orderPhotoLib = new OrderPhotoLib();
        orderPhotoLib.setOrderId(id);
        List<OrderPhotoLib> list = orderPhotoLibService.getList(orderPhotoLib);
        ArrayList<String> images = new ArrayList<>();
        for (OrderPhotoLib photoLib : list) {
            images.add(photoLib.getImageUrl());
        }
        vo.setImageList(images);
        vo.setWorkOrderInfo(workOrderInfoService.getOneById(id));
        WorkOrderProcess processWhere = new WorkOrderProcess();
        processWhere.setOrderId(id);
        List<WorkOrderProcess> list1 = workOrderProcessService.getList(processWhere);
        for (WorkOrderProcess workOrderProcess : list1) {
            if(!StringUtils.isEmpty(workOrderProcess.getImgPath())){
                workOrderProcess.setPreviewImgPathList(Arrays.asList(workOrderProcess.getImgPath().split(",")));
            }
        }
        vo.setProcessList(list1);
        WorkOrderReview reviewWhere = new WorkOrderReview();
        reviewWhere.setOrderId(id);
        vo.setReviewList(workOrderReviewService.getList(reviewWhere));
        vo.setImageLocations(list);
        return RespJSON.success(vo);
    }

    /**
     * 已接单工单
     * @param ids
     * @return RespJSON
     */
    @PostMapping("/receivedOrder")
    public RespJSON receivedOrder(String ids) {
        WJAssert.notNull(ids, "ID 不合法");
        String[] split = ids.split(",");
        ArrayList<Long> longs = new ArrayList<>();
        for (String s : split) {
            WorkOrderInfo orderInfo = workOrderInfoService.getOneById(Long.valueOf(s));
            if(orderInfo!=null&&orderInfo.getOrderStatus()!=0){
                longs.add(orderInfo.getId());
            }
        }
        return RespJSON.success(longs);
    }

    /**
     * 催单
     * @param id id
     * @return RespJSON
     */
    @PostMapping("/reminders")
    @RoleCheck(name = "work_order_remind")
    public RespJSON reminders(Long id, @SessionAttribute(CurrentUserUtils.SYSTEM_USER)SysUser loginSysUser) {
        WJAssert.notNull(id, "ID 不合法");
        if(!workOrderInfoService.canItBeUrged(id,loginSysUser.getId())){
            throw new BusinessException("此任务单已经催过单了，请稍后重试！");
        }
        workOrderInfoService.reminders(id, loginSysUser.getName(),loginSysUser.getId());
        return RespJSON.success();
    }

    /**
     * 接单
     * @param id id
     * @return RespJSON
     */
    @PostMapping("/acceptOrder")
    @RoleCheck(name = "work_order_accept")
    public RespJSON acceptOrder(Long id, @SessionAttribute(CurrentUserUtils.SYSTEM_USER)SysUser loginSysUser) {
        WJAssert.notNull(id, "ID 不合法");
        workOrderInfoService.acceptOrder(id, loginSysUser);
        return RespJSON.success();
    }

    @PostMapping("/remove")
    @RoleCheck(name = "work_order_remove")
    public RespJSON remove(Long id,@SessionAttribute(CurrentUserUtils.SYSTEM_USER) SysUser loginSysUser) {
        WJAssert.notNull(id, "ID 不合法");
        workOrderInfoService.delete(id, loginSysUser.getUserName());
        return RespJSON.success();
    }

}
